#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>

namespace myMutex{
    class Mutex{
    public:
        Mutex()
        {
            int id = pthread_mutex_init(&_lock, nullptr);
            if(id != 0) {std::cout << "Mutex Init Error!" << std::endl;}
        }

        ~Mutex(){
            int id = pthread_mutex_destroy(&_lock);
            if(id != 0) {std::cout << "Mutex Destroy Error!" << std::endl;}
        }

        void Lock(){
            int id = pthread_mutex_lock(&_lock);
            if(id != 0) {std::cout << "Mutex Lock Error!" << std::endl;}
        }

        void UnLock(){
            int id = pthread_mutex_unlock(&_lock);
            if(id != 0) {std::cout << "Mutex UnLock Error!" << std::endl;}
        }

        pthread_mutex_t* GetLockAddr(){
            return &_lock;
        }

    private:
        pthread_mutex_t _lock;
    };


// RAII思想加锁 / 解锁 ，锁的创建和删除由Mutex类自己完成
    class Lock_Guard{
    public:
        Lock_Guard(myMutex::Mutex& lock)
            :_lock(lock)
        {
            // 创建Lock_Guard的时候自动加锁
            _lock.Lock();
        }

        ~Lock_Guard(){
            _lock.UnLock();
        }

    private:
        Mutex& _lock;
    };

}



